package com.tool.engine.export.mertics.collect;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class WindowCollect{
    private static final int MAX_RECORDS = 1024;
    private static final int INDEX_MASK = MAX_RECORDS - 1;
    private final NumberRecord[] circularBuffer = new NumberRecord[MAX_RECORDS];
    private final AtomicInteger currentPosition = new AtomicInteger(0);

    public void addValue(long value, int size) {
        int pos = currentPosition.getAndIncrement();
        circularBuffer[pos & INDEX_MASK] = new NumberRecord(value, size);
    }

    public void addValue(double value, int size) {
        int pos = currentPosition.getAndIncrement();
        circularBuffer[pos & INDEX_MASK] = new NumberRecord(value, size);
    }

    public synchronized List<NumberRecord> getValues() {
        NumberRecord[] snapshot = circularBuffer.clone();
        int size = Math.min(currentPosition.get(), MAX_RECORDS);
        List<NumberRecord> result = new ArrayList<>(size);
        int start = currentPosition.get() & INDEX_MASK;
        if(size < MAX_RECORDS) {
            start=0;
        }
        for (int i = 0; i < size; i++) {
            NumberRecord value = snapshot[(start + i) & INDEX_MASK];
            if (value != null) {
                result.add(value);
            }
        }
        return result;
    }
}
